package whu.o2o.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import android.util.Log;

public class FileService {

	  public static final String TAG = "FileService";  
      private static Context context;  

      //�õ�����������Ķ��������  
      public FileService(Context context) {  
          this.context = context;  
      }  

      /** 
       * �����ļ� 
       *  
       * @param fileName �ļ��� 
       * @param content  �ļ����� 
       * @throws Exception 
       */  
      public   void saveFile(String dir,String fileName, String content) {  
          // ����ҳ������Ķ����ı���Ϣ�����Ե��ļ�������.txt��׺���βʱ���Զ�����.txt��׺  
          if (!fileName.endsWith(".txt")) {  
              fileName = fileName + ".txt";  
          }  
          try
          {
          File sdDir = new File("/sdcard/");
	        if (sdDir.exists() && sdDir.canWrite()) {
	            File uadDir = new File(sdDir.getAbsolutePath() + "/dcjr/"+dir);
	            uadDir.mkdir();
	            if (uadDir.exists() && uadDir.canWrite()) {
	                File file = new File(uadDir.getAbsolutePath() + "/" + fileName);
	                try {
	                    file.createNewFile();
	                } catch (IOException e) {
	                    Log.e("ImageUtil", "error creating file", e);
	                }

	                if (file.exists() && file.canWrite()) {
	                    FileOutputStream fos = null;
	                    try {
	                    	fos = context.openFileOutput(fileName, context.MODE_PRIVATE);  
	                        fos.write(content.getBytes());  
	                        fos.close();  
	                    } catch (FileNotFoundException e) {
	                        Log.e("ImageUtil", "ERROR", e);
	                    } catch (Exception e) {
	                        Log.e("ImageUtil", "ERROR", e);
	                    } finally {
	                        if (fos != null) {
	                            try {
	                                fos.flush();
	                                fos.close();
	                            } catch (IOException e) {
	                                // swallow
	                            }
	                        }
	                    }
	                } else {
	                    Log.e("ImageUtil", "error writing to file");
	                }
	                
	            }
	            
	          }
          }catch(Exception e)
          {
        	  e.printStackTrace();
          }
             }  

      /** 
       * ��ȡ�ļ����� 
       *  
       * @param fileName �ļ��� 
       * @return �ļ����� 
       * @throws Exception 
       */  
      public   String readFile(String dir,String fileName) throws Exception {  

          // ����ҳ������Ķ����ı���Ϣ�����Ե��ļ�������.txt��׺���βʱ���Զ�����.txt��׺  
          if (!fileName.endsWith(".txt")) {  
              fileName = fileName + ".txt";  
          }  
          File rFile = new File("/sdcard/dcjr/"+dir+"/" + fileName);
          FileInputStream fis = null;
          fis=new FileInputStream(rFile);
          ByteArrayOutputStream baos = new ByteArrayOutputStream();  
          byte[] buf = new byte[1024];  
          int len = 0;  

          //����ȡ�����ݷ������ڴ���---ByteArrayOutputStream  
          while ((len = fis.read(buf)) != -1) {  
              baos.write(buf, 0, len);  
          }  
          fis.close();  
          baos.close();  

          //�����ڴ��д洢�����  
          return baos.toString();
      }
      
      /**
       * ɾ���ļ����ڵ������ļ�
       * @param filepath
       * @throws IOException
       */
      public void deleteFile(String filepath)
      {  
    	  try
    	  {
                        File f = new File(filepath);//�����ļ�·��         
                        File delFile[]=f.listFiles();  
                        if(delFile!=null)
                        {
                            int i =f.listFiles().length;  
                            for(int j=0;j<i;j++)
                            {
                                delFile[j].delete();//ɾ���ļ�
                            }
                        }
    	  }catch(Exception e)
    	  {
    		  e.printStackTrace();
    	  }
      }
      
      /**
       * ��������ļ���
       * @param pathname
       */
      public void createFile(String pathname)
      {
    	  File sdDir = new File("/sdcard/");
	        if (sdDir.exists() && sdDir.canWrite()) 
	        {
	            File uadDir = new File(sdDir.getAbsolutePath()+"/"+pathname);
	            uadDir.mkdirs();
	        }
      }
      
      
      /**
  	 *	Reads a file and returns its contents as an array of bytes
  	 *	@param	file	The file object to read from
  	 *	@return The contents of the file as an array of bytes
  	 */
  	public static byte[] readByteFile(File file){		
  		byte data[] = null;
  		try{
  			FileInputStream fis = new FileInputStream(file);
  			int c,i=0;
  			data = new byte[(int)file.length()];
  			while ((c = fis.read()) != -1){
  	  		    data[i++] = (byte)c;
  			}
  			System.out.println(file.length()+"&&&"+data.length);
  			fis.close();
  		}
  		catch(IOException e){
  			e.printStackTrace();
  			return null;
  		}				
  		return data;
  	}
  	
  	/**
  	 *	Writes byte contents to a file
  	 *	@param file	The file object to write to
  	 *	@param data	The data (array of bytes) to write
  	 *	@return Whether the process is successful
  	 */
  	protected boolean writeByteFile(String fileName, byte[] data){
  		File file = new File(fileName);
  		if (!file.canWrite()){
  			try {file.createNewFile();}
  			catch(IOException e){
  				e.printStackTrace();
  				return false;
  			}
  		}		
  		try{			
  			FileOutputStream fos = new FileOutputStream(file);
  			fos.write(data);
  			fos.close();
  			return true;
  		}
  		catch(IOException e){
  		e.printStackTrace();
  		return false;
  		}
  	}	

  	/**
  	 *	Reads a file and returns its contents as an array of objects
  	 *	@param	file	The file object to read from
  	 *	@return The contents of the file as an array of objects
  	 */
  	protected Object readObjectFile(File file){		
  		Object obj=null;
  		try{
  			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
  		    obj = (Object)ois.readObject();
  			ois.close();			
  		}
  		catch(IOException e){
  			e.printStackTrace();
  			return null;
  		}
  		catch(ClassNotFoundException e){
  			e.printStackTrace();
  			return null;
  		}			
  		return obj;
  	}
  	
  	/**
  	 *	Writes an object to a file
  	 *	@param file	The file object to write to
  	 *	@param data	The data (single instance of an object) to write
  	 *	@return Whether the process is successful
  	 */
  	protected boolean writeObjectFile(String fileName, Object data){
  		File file = new File(fileName);
  		if (!file.canWrite()){
  			try {file.createNewFile();}
  			catch(IOException e){
  				e.printStackTrace();
  				return false;
  			}
  		}		
  				
  		try{
  			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
  		    oos.writeObject(data);
  			oos.close();
  			return true;
  		}
  		catch(IOException e){
  			e.printStackTrace();
  			return false;
  		}
  	}	
      
}
